package core.proto;

import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Hashtable;
import java.util.LinkedList;

import org.apache.commons.io.FilenameUtils;

import static app.constants.CollabVizConstants.*;

/**
 * The purpose class is to manage all the user annotations thus far entered. 
 * It is also responsible for saving them to disk. 
 * @author Wei Xin Yuan
 *
 */
public class AnnotationManager {
	private static Hashtable<String, Collection<Annotation>> store; 

	static {
		File f = new File(ANNOTATIONS_FOLDER);
		if (! f.exists()){
			f.mkdir();
		}
		store = new Hashtable<String, Collection<Annotation>>();
		
		// TODO load up the store.
		// for now just read the directory. 
		if (f.isDirectory()){
			File[] annotations = f.listFiles();
			BufferedReader reader; 
			for (File annoFile : annotations){
				try {
					reader = new BufferedReader(new FileReader(annoFile));
					String line;
					while ((line = reader.readLine()) != null){
						if (! line.trim().equals("")){
							Annotation a = new Annotation(line);
							if (! store.containsKey(a.docKey)){
								store.put(a.docKey, new LinkedList<Annotation>());
							}
							store.get(a.docKey).add(a);
						}
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * When this is called, the annotation, highlight file for the case with 
	 * the given key is updated. 
	 * @param key Usually the case name. 
	 */
	public static void writeFile(String key){
		File f = new File(FilenameUtils.concat(ANNOTATIONS_FOLDER, key + ".txt"));
		if (f.exists()){
			f.delete(); // clean start. 
		}
		PrintWriter writer = null;
		if (store.containsKey(key) && store.get(key).size() > 0){
			try {
				
				writer = new PrintWriter(new FileWriter(f));
				for (Annotation anno : store.get(key)){
					writer.println(anno.toSerializeString());
				}
			} catch (IOException e) {
				System.err.println(e.getStackTrace());
			} finally {
				if (writer != null){
					writer.flush();
					writer.close();
				}
			}
		}
	}

	public static void addAnnotation(String key, Annotation value){
		if (! store.containsKey(key)){
			store.put(key, new LinkedList<Annotation>());
		}
		store.get(key).add(value);
	}

	public static void removeAnnotation(String key, Annotation value){
		if (store.containsKey(key)){
			store.get(key).remove(value);
		}
	}
	
	public static Iterable<Annotation> getAnnotations(String key){
		if (store.containsKey(key)){
			return store.get(key);
		}
		return new LinkedList<Annotation>();
	}
}
